import type { AsyncData, UseFetchOptions } from "#app";

// 常量定义
const DEFAULT_TIMEOUT = 10000;
const SUCCESS_CODE = 200;
const UNAUTHORIZED_CODE = 401;
const INTERNAL_SERVER_ERROR_CODE = 500;
const CUSTOM_ERROR_CODE = 601;

// 是否显示重新登录
export let isRelogin = { show: false };

export const request = {
  useFetch: <T>(url: string, options: UseFetchOptions<T> = {}): Promise<AsyncData<any,any>> => {
    const config = useRuntimeConfig();

    if (isEmpty(options.server)) {
      options.server = true;
    }

    const defaults: UseFetchOptions<T> = {
      baseURL: (options.server ? config.public.appBaseUrl : "") + config.public.appBaseApi,
      onRequest({ options }) {
        onRequest(options);
      },
      timeout: DEFAULT_TIMEOUT,
      onResponseError({ response }) {
        // console.error('Response error:', response.status, response._data);
        response._data = { error: ref("请求失败，请重试") };
      },
    };

    return useFetch(url, {
      ...defaults,
      ...options
    }).then((response: any) => {
      handleResponse(response);
      return response;
    });
  }
}

function onRequest(options: { headers: Headers }) {
  options.headers.set('Authorization', getToken());
  options.headers.set('Accept', 'application/json');
}

const handleResponse = <T>(response: AsyncData<any, any>) => {
  // console.log(response, 'response');
  const { data, error } = response;
  // 未设置状态码则默认成功状态
  const code = data.value.code || SUCCESS_CODE;
  // 获取错误信息
  const msg = errorCode[code] || data.value.msg || errorCode['default'];
  if (code === UNAUTHORIZED_CODE) {
    if (!isRelogin.show) {
      isRelogin.show = true;
      ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isRelogin.show = false;
        // 登陆跳转
      }).catch(() => {
        isRelogin.show = false;
      });
    }
    error.value = "无效的会话，或者会话已过期，请重新登录";
  } else if (code === INTERNAL_SERVER_ERROR_CODE) {
    ElMessage({ message: msg, type: 'error' });
    error.value = msg;
  } else if (code === CUSTOM_ERROR_CODE) {
    ElMessage({ message: msg, type: 'warning' });
    error.value = msg;
  } else if (code !== SUCCESS_CODE) {
    ElMessage({ message: msg, type: 'error' });
    error.value = msg;
  }
}